package com.rongxue.service.utils;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.rongxue.pojo.SUserDueDetail;
import com.rongxue.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class PDFHelper {
	private static Logger LOG = LoggerFactory.getLogger(PDFHelper.class);

	public static  Map<String, String> map = new HashMap<>();

//	public static String inUrl = "E:/sign/pdf1/rongji.pdf";
//	public static String Url= "E:/sign/pdf2/";

	public static String inUrl = "/usr/local/tomcat/apache-tomcat-7.0.88/webapps/public/pdf/rongji.pdf";//模板pdf路径
	public static String Url= "/usr/local/tomcat/apache-tomcat-7.0.88/webapps/public/pdf/";//生成未盖章pdf路径

	public static String prefixFont = "C:/WINDOWS/Fonts/SIMSUN.TTC,1";//winodws系统中文字体
//	public static String prefixFont ="/usr/share/fonts/chinese/MSYH.ttf";//linux系中文统字体


	/**
	 * 将pdf域填上内容
	 */
	public static String PDFFill(Map<String,Object> data){

		 String outUrl= Url +DateUtil.formatDate();
		 createDirectory(outUrl);
		 outUrl +=  "/" +data.get("contractNo")+".pdf";

		OutputStream os = null;
		PdfStamper ps = null;
		PdfReader reader = null;

		try {
			// 1 读取pdf表单
			reader = new PdfReader(inUrl);
			// 2 输出pdf表单
			os = new FileOutputStream(outUrl);
			// 3 根据表单生成一个新的pdf
			ps = new PdfStamper(reader, os);
			// 4 获取pdf表单
			AcroFields form = ps.getAcroFields();
			// 5给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示
			BaseFont bf = BaseFont.createFont(prefixFont,
					BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			form.addSubstitutionFont(bf);
			// 6查询数据================================================

			String contract_no = "RJ"+DateUtil.formatLongDateTime();


			// 7遍历data 给pdf表单表格赋值
			for (String key : data.keySet()) {
				form.setField(key,data.get(key).toString());
			}
			ps.setFormFlattening(true);

			//-----------------------------pdf 添加图片----------------------------------
			// 通过域名获取所在页和坐标，左下角为起点
//            System.out.println("pdf 添加图片");
			// String imgpath="E:/sign/pdf2/ddddd.pdf";
//            int pageNo = form.getFieldPositions("img").get(0).page;
//            Rectangle signRect = form.getFieldPositions("img").get(0).position;
//            float x = signRect.getLeft();
//            float y = signRect.getBottom();
//            // 读图片
//            Image image = Image.getInstance(imgpath);
//            // 获取操作的页面
//            PdfContentByte under = ps.getOverContent(pageNo);
//            // 根据域的大小缩放图片
//            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
//            // 添加图片
//            image.setAbsolutePosition(x, y);
//            under.addImage(image);
			//-------------------------------------------------------------
			LOG.info("===============PDF导出成功=============");
			return outUrl;
		} catch (Exception e) {
			LOG.info("===============PDF导出失败=============");
			e.printStackTrace();
			return null;
		} finally {
			try {
				ps.close();
				reader.close();
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/***
	 * 创建文件夹
	 *
	 * @param folderPath
	 * @return
	 */
	public static boolean createDirectory(String folderPath) {
		boolean isSuccess = false;
		File file = new File(folderPath);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
			isSuccess = true;
		} else {
			isSuccess = true;
		}
		return isSuccess;
	}

	public static void main(String[] args) {
		Map<String,Object> map = new HashMap<>();
		String contractNo = "RJ"+ DateUtil.formatLongDateTime();
		map.put("contractNo",contractNo);
		map.put("financing","杨伟俭");
		map.put("rechargeNo","Rj12231534865784");
		map.put("amount",9200d);
		map.put("idcard","330327199202281853");
		PDFFill(map);
	}
}
